package com.cysyz.web.modules.base.support.filter;


import com.cysyz.mylib.utils.scanner.PackageScanner;
import com.cysyz.web.modules.base.permission.annotation.Module;
import com.cysyz.web.modules.base.support.ServletActionContext;
import com.cysyz.web.modules.base.support.ThreadLocalContext;
import com.cysyz.web.modules.base.support.path.ProjectRealPathAware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.EnvironmentAware;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 为实现了{@link ProjectRealPathAware}的类设置项目的绝对路径
 */
@WebFilter(urlPatterns = "")
@Component
public class ProjectRealPathAwareProcessorFilter implements Filter, BeanPostProcessor {
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

        ThreadLocalContext context = ServletActionContext.getContext();
        if (context == null) {
            ThreadLocalContext.createNewContext();
        }
        ServletActionContext.setRequest((HttpServletRequest) request);
        ServletActionContext.setResponse((HttpServletResponse) response);

        chain.doFilter(request, response);

        ServletActionContext.remove();
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		for (ProjectRealPathAware bean : projectRealPathAwareList) {
			bean.setRealPath(filterConfig.getServletContext().getRealPath(""));
		}
	}

	private static List<ProjectRealPathAware> projectRealPathAwareList = new ArrayList<ProjectRealPathAware>();
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

		if (bean instanceof ProjectRealPathAware) {
			projectRealPathAwareList.add((ProjectRealPathAware) bean);
		}

		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

		return bean;
	}
}
